/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * ControlPrenez.java
 *
 * Created on 14-dic-2011, 13:05:34
 */
package formularios;

import clases.ConversorRSaDefaultTableModel;
import clases.ProcesarTxt;
import clases.abmBovino;
import clases.conexion;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author Elio
 */
public class ControlStock extends javax.swing.JDialog {
    String consultainicial="";
    String identificacion="";
  //  DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
    /** Creates new form ControlPrenez */
    public ControlStock(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        this.setTitle("Control de Stock");
        consultainicial="SELECT fecha, count(identificacion) as cantidad FROM controles c where idControl=5 group by fecha";
        CrearTabla(consultainicial,tablaStock,modelo);
    //    calendarioDesde.setDateFormat(df);
   //     calendarioDesde.repaint();
        
        
       //calendarioDesde.setDateFormat(java.text.DateFormat.);
    }
    
    public void Conectar(){
        try{
            mdbc = new conexion();
            mdbc.init();
            Connection conn= mdbc.getMyConnection();
            stmt = conn.createStatement();
        }catch(Exception ex)
        {
            JOptionPane.showMessageDialog(null, "Problemas al concetarse a la Base de Datos","Error",JOptionPane.ERROR_MESSAGE);
        }
    }
    
     private void CrearTabla(String sql, JTable tabla, DefaultTableModel mode){
      
          try {
            Conectar();
            ResultSet rs = stmt.executeQuery(sql);

      
            tabla.setModel(mode);
            tabla.setAutoResizeMode(tabla.AUTO_RESIZE_ALL_COLUMNS);
              
                    
            ConversorRSaDefaultTableModel.completar(rs, mode);

        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null, "Error en la consulta de control preñez" + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
        }
        
    }
    
    private conexion mdbc;
    private Statement stmt;
    private DefaultTableModel modelo = new DefaultTableModel();
    private DefaultTableModel modelo2 = new DefaultTableModel();

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        VerFichaAnimal = new javax.swing.JPopupMenu();
        FichaAnimal = new javax.swing.JMenuItem();
        jLabel1 = new javax.swing.JLabel();
        jPanel1 = new javax.swing.JPanel();
        btnNuevoControlPreñez = new javax.swing.JButton();
        panelConsultas = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tablaStock = new javax.swing.JTable();
        tabPanelBuscarAnimal = new javax.swing.JTabbedPane();
        listaranimales = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        existentes = new javax.swing.JTable();

        FichaAnimal.setIcon(new javax.swing.ImageIcon(getClass().getResource("/iconos/modifica.png"))); // NOI18N
        FichaAnimal.setText("Ver ficha del animal");
        FichaAnimal.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                FichaAnimalMouseClicked(evt);
            }
        });
        FichaAnimal.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                FichaAnimalActionPerformed(evt);
            }
        });
        VerFichaAnimal.add(FichaAnimal);

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 14));
        jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel1.setText("Control Stock");

        jPanel1.setLayout(new java.awt.GridLayout(1, 2));

        btnNuevoControlPreñez.setText("Nuevo Control");
        btnNuevoControlPreñez.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnNuevoControlPreñezActionPerformed(evt);
            }
        });
        jPanel1.add(btnNuevoControlPreñez);

        tablaStock.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        tablaStock.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tablaStockMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(tablaStock);

        existentes.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null, null},
                {null, null, null, null, null},
                {null, null, null, null, null},
                {null, null, null, null, null}
            },
            new String [] {
                "Identificacion", "Num Senasa", "Sexo", "Categoria", "Color caravana"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        existentes.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                existentesMouseClicked(evt);
            }
        });
        jScrollPane2.setViewportView(existentes);
        existentes.getColumnModel().getColumn(0).setResizable(false);
        existentes.getColumnModel().getColumn(1).setResizable(false);
        existentes.getColumnModel().getColumn(2).setResizable(false);
        existentes.getColumnModel().getColumn(3).setResizable(false);
        existentes.getColumnModel().getColumn(4).setResizable(false);

        javax.swing.GroupLayout listaranimalesLayout = new javax.swing.GroupLayout(listaranimales);
        listaranimales.setLayout(listaranimalesLayout);
        listaranimalesLayout.setHorizontalGroup(
            listaranimalesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 541, Short.MAX_VALUE)
        );
        listaranimalesLayout.setVerticalGroup(
            listaranimalesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(listaranimalesLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 98, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(340, Short.MAX_VALUE))
        );

        tabPanelBuscarAnimal.addTab("Animales existentes", new javax.swing.ImageIcon(getClass().getResource("/iconos/existentes.png")), listaranimales); // NOI18N

        javax.swing.GroupLayout panelConsultasLayout = new javax.swing.GroupLayout(panelConsultas);
        panelConsultas.setLayout(panelConsultasLayout);
        panelConsultasLayout.setHorizontalGroup(
            panelConsultasLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelConsultasLayout.createSequentialGroup()
                .addGap(27, 27, 27)
                .addGroup(panelConsultasLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(tabPanelBuscarAnimal, javax.swing.GroupLayout.DEFAULT_SIZE, 546, Short.MAX_VALUE)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 546, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(40, 40, 40))
        );
        panelConsultasLayout.setVerticalGroup(
            panelConsultasLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelConsultasLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 189, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(tabPanelBuscarAnimal)
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 613, Short.MAX_VALUE)
                            .addComponent(panelConsultas, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addContainerGap())
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 544, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(52, 52, 52))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 46, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(panelConsultas, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-649)/2, (screenSize.height-489)/2, 649, 489);
    }// </editor-fold>//GEN-END:initComponents

private void btnNuevoControlPreñezActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnNuevoControlPreñezActionPerformed
    // 2 = Stock
    new ProcesarTxt().LeerControlStock(2);
    CrearTabla(consultainicial, tablaStock,modelo);
    existentes.repaint();
}//GEN-LAST:event_btnNuevoControlPreñezActionPerformed

    private void tablaStockMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tablaStockMouseClicked
         int fila = tablaStock.getSelectedRow();
       
       if ((fila > -1)){
            String fecha= String.valueOf(tablaStock.getValueAt(fila,0)); 
            String consulta= "SELECT c.identificacion,b.NumSenasa as 'N° Senasa',"
                    + " b.sexo, p.descripcion as 'Pelaje', "
                    + "tb.descripcion as 'Categoria', "
                    + "b.ColorCaravana as 'Color caravana'  "
                    + "FROM controles c, bovino b, pelaje p, tipobovino tb where "
                    + "idControl=2 and fecha='"+fecha+"' and "
                    + " c.identificacion=b.identificacion and"
                    + " b.idtipobovino = tb.idtipobovino and "
                    + "b.idpelaje = p.idpelaje";
            CrearTabla(consulta,existentes,modelo2);
            System.out.println(fecha);
       }
           
            
   
    }//GEN-LAST:event_tablaStockMouseClicked

    private void existentesMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_existentesMouseClicked
 int fila = existentes.rowAtPoint(evt.getPoint()); 

         int columna = existentes.columnAtPoint(evt.getPoint());
         if ((fila > -1) && (columna == 0)){
         identificacion = String.valueOf(modelo2.getValueAt(fila,columna)); 
         VerFichaAnimal.show(existentes, fila, columna);
         }
        
   
    }//GEN-LAST:event_existentesMouseClicked

    private void FichaAnimalMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_FichaAnimalMouseClicked
        new FichaAnimal(identificacion).setVisible(true);
    }//GEN-LAST:event_FichaAnimalMouseClicked

    private void FichaAnimalActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_FichaAnimalActionPerformed
new FichaAnimal(identificacion).setVisible(true);
    }//GEN-LAST:event_FichaAnimalActionPerformed

     public String convertirFecha(String FechaA){
      String anio,mes,dia;
     //30112011
      anio=FechaA.substring(6,10);
      mes=FechaA.substring(3,5);
      dia=FechaA.substring(0,2);
      String Fecha=anio+"-"+mes+"-"+dia;
      return Fecha;

    }
    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(ControlPrenez.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(ControlPrenez.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(ControlPrenez.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(ControlPrenez.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the dialog */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                ControlStock dialog = new ControlStock(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {

                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
        
        //jFormattedTextField1.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.DateFormatter(java.text.DateFormat.getDateInstance(java.text.DateFormat.FULL))));
    }
    private boolean ninja = false;
    private String fecha;
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JMenuItem FichaAnimal;
    private javax.swing.JPopupMenu VerFichaAnimal;
    private javax.swing.JButton btnNuevoControlPreñez;
    private javax.swing.JTable existentes;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JPanel listaranimales;
    private javax.swing.JPanel panelConsultas;
    private javax.swing.JTabbedPane tabPanelBuscarAnimal;
    private javax.swing.JTable tablaStock;
    // End of variables declaration//GEN-END:variables
}
